<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use cmf\controller\RestBaseController;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Qiniu\Processing\PersistentFop;


class UploadController extends RestBaseController
{
     public function _initialize()
    {
         $pluginClass = cmf_get_plugin_class('Qiniu');
       
        $this->plugin = new $pluginClass();
        $this->config = $this->plugin->getConfig();

        $this->storageRoot = $this->config['protocol'] . '://' . $this->config['domain'] . '/';
       
    }
    // 用户密码修改
    public function one()
    {
        $file = $this->request->file('file');
        // 移动到框架应用根目录/public/upload/ 目录下
        $info     = $file->validate([
            /*'size' => 15678,*/
            'ext' => 'jpg,png,gif'
        ]);
        $fileMd5  = $info->md5();
        $fileSha1 = $info->sha1();

        $findFile = Db::name("asset")->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();

        if (!empty($findFile)) {
            $this->success("上传成功!", ['url' => $findFile['file_path'], 'filename' => $findFile['filename']]);
        }
        $info = $info->move(ROOT_PATH . 'public' . DS . 'upload');
        if ($info) {
            $saveName     = $info->getSaveName();
            $originalName = $info->getInfo('name');//name,type,size
            $fileSize     = $info->getInfo('size');
            $suffix       = $info->getExtension();

            $fileKey = $fileMd5 . md5($fileSha1);

            $userId = $this->getUserId();
            Db::name('asset')->insert([
                'user_id'     => $userId,
                'file_key'    => $fileKey,
                'filename'    => $originalName,
                'file_size'   => $fileSize,
                'file_path'   => $saveName,
                'file_md5'    => $fileMd5,
                'file_sha1'   => $fileSha1,
                'create_time' => time(),
                'suffix'      => $suffix
            ]);

            $this->success("上传成功!", ['url' => $saveName, 'filename' => $originalName]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }

    }



     // 上传图片以及视频至七牛云
    public function upload_img()
    {

        $file = $this->request->file('file');
		//dump($file);
        $info     = $file->validate([
            'size' => 10,
            'ext' => 'jpg,png,gif'
        ]);
        $filePath = $file->getRealPath();
      //echo $filePath;
		/*$this->error('上传失败!',$filePath);
		exit;*/
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        //var_dump($this->config);
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $watermark = $this->config['styles_watermark'];
        $upManager = new UploadManager();
        $auth      = new Auth($accessKey, $secretKey);
        $token     = $auth->uploadToken($this->config['bucket']);

        $result = $upManager->putFile($token, $key, $filePath);
        //var_dump($result);die;
        $previewUrl = $this->getPreviewUrl($key, $watermark);

        $url        = $this->getImageUrl($key, $watermark);
        $this->success("上传成功!", ['url' => $previewUrl, 'filename' => $url]);
    }


     // 上传视频至七牛云
    public function upload_video()
    {

        $file = $this->request->file('file');
        $info     = $file->validate([
            'size' => 10,
        ]);
        $filePath = $file->getRealPath();
		
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        //var_dump($this->config);die;
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $watermark = $this->config['styles_watermark'];
         $auth      = new Auth($accessKey, $secretKey);


         $upManager = new UploadManager();
        $token     = $auth->uploadToken($this->config['bucket']);

        $result = $upManager->putFile($token, $key, $filePath);

        //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
        $pipeline = '20180115';
        $force = false;

        //转码完成后通知到你的业务服务器。
        $notifyUrl = 'http:'.$_SERVER['HTTP_HOST'].'/notify.php';
        $config = $this->config;
        //$config->useHTTPS=true;

        $pfop = new PersistentFop($auth, $config);

        //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
        $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . \Qiniu\base64_urlSafeEncode($this->config['bucket'] . ":".$key);

        list($id, $err) = $pfop->execute($this->config['bucket'], $key, $fops, $pipeline, $notifyUrl, $force);

        //查询转码的进度和状态
        list($ret, $err) = $pfop->status($id);
       // echo "\n====> pfop avthumb status: \n";
        if ($err != null) {
            $this->error('上传失败!');
        } else {
            //成功
            $this->success("上传成功!", ['url' => 'http://'.$this->config['domain'].'/'.$key]);
        }

     
    }



    // 上传语音至七牛云
    public function upload_voice()
    {

        $file = $this->request->file('file');
       
        $filePath = $file->getRealPath();
      
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        //var_dump($this->config);die;
        $accessKey = $this->config['accessKey'];
        $secretKey = $this->config['secretKey'];
        $watermark = $this->config['styles_watermark'];
        $upManager = new UploadManager();
        $auth      = new Auth($accessKey, $secretKey);

        $name=substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999);

         //$bucket = 'radio';
        //数据处理队列名称,不设置代表不使用私有队列，使用公有队列。
        $pipeline = '20180115';

        //通过添加'|saveas'参数，指定处理后的文件保存的bucket和key
        //不指定默认保存在当前空间，bucket为目标空间，后一个参数为转码之后文件名
        $savekey = \Qiniu\base64_urlSafeEncode($this->config['bucket'].':'.$name.'.mp3');
        //设置转码参数
        $fops = "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame";
        $fops = $fops.'|saveas/'.$savekey;
        if(!empty($pipeline)){  //使用私有队列
            $policy = array(
                'persistentOps' => $fops,
                'persistentPipeline' => $pipeline
            );
        }else{                  //使用公有队列
            $policy = array(
                'persistentOps' => $fops
            );
        }


        //指定上传转码命令
        $token = $auth->uploadToken($this->config['bucket'], null, 3600, $policy);

        //$token     = $auth->uploadToken($this->config['bucket']);
        list($ret, $err) = $upManager->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        }else {
            //此时七牛云中同一段音频文件有amr和MP3两个格式的两个文件同时存在
            $bucketMgr = new BucketManager($auth);
            //为节省空间,删除amr格式文件
            $bucketMgr->delete($this->config['bucket'], $key);
        }

        $previewUrl = $this->getPreviewUrl($name.'.mp3', $watermark);

        $url        = $this->getImageUrl($name.'.mp3', $watermark);
        $this->success("上传成功!", ['url' => $previewUrl, 'filename' => $url]);
    }


     // 上传语音转码至七牛云
    public function upload_voice2()
    {

         $file = $this->request->file('file');
         $info     = $file->validate([
            /*'size' => 15678,*/
            'ext' => 'amr,wav,pcm'
        ]);
        $info = $info->move(ROOT_PATH . 'public' . DS . 'upload/sound');
        $filename = $info->getSaveName();
        $path =ROOT_PATH . 'public' . DS . 'upload/sound/'. $filename;
        $name = substr($path,0,strlen($path)-4);
        //var_dump($name);die;
        $re=$this->zhuanma($path,$name.'.pcm');
        
        if($re == 0){

            //转码成功,删除原文件
            unlink($path);
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
            // 上传到七牛后保存的文件名
            $key =substr(md5($file->getPathName()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
            $accessKey = $this->config['accessKey'];
            $secretKey = $this->config['secretKey'];
            $watermark = $this->config['styles_watermark'];
            $upManager = new UploadManager();
            $auth      = new Auth($accessKey, $secretKey);

            $name2 = substr(md5($file->getPathName()) , 0, 5). date('YmdHis') . rand(0, 9999);
           //数据处理队列名称,不设置代表不使用私有队列，使用公有队列。
            $pipeline = '20180115';

            //通过添加'|saveas'参数，指定处理后的文件保存的bucket和key
            //不指定默认保存在当前空间，bucket为目标空间，后一个参数为转码之后文件名
            $savekey = \Qiniu\base64_urlSafeEncode($this->config['bucket'].':'.$name2.'.mp3');
            //设置转码参数
            $fops = "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame";
            $fops = $fops.'|saveas/'.$savekey;
            if(!empty($pipeline)){  //使用私有队列
                $policy = array(
                    'persistentOps' => $fops,
                    'persistentPipeline' => $pipeline
                );
            }else{                  //使用公有队列
                $policy = array(
                    'persistentOps' => $fops
                );
            }


            //指定上传转码命令
            $token = $auth->uploadToken($this->config['bucket'], null, 3600, $policy);

            //$token     = $auth->uploadToken($this->config['bucket']);
            list($ret, $err) = $upManager->putFile($token, $key, $name.'.pcm');
            if ($err !== null) {
                return false;
            }else {
                //此时七牛云中同一段音频文件有amr和MP3两个格式的两个文件同时存在
                $bucketMgr = new BucketManager($auth);
                //为节省空间,删除amr格式文件
                $bucketMgr->delete($this->config['bucket'], $key);
            }

           
            $previewUrl = $this->getPreviewUrl($ret['key'], $watermark);

            $url        = 'http://'.$_SERVER['HTTP_HOST'].'/upload/sound/'.substr($filename,0,strlen($filename)-4).'.pcm';
            //var_dump($name);die;
            $this->success("上传成功!", ['url' => $previewUrl, 'filename' =>$url,'path'=>substr($filename,0,strlen($filename)-4).'.pcm']);
        }else{
            $this->error('上传失败');
        }
        


       
       
    }

     /**
     * 获取图片预览地址
     * @param string $file
     * @param string $style
     * @return mixed
     */
    public function getPreviewUrl($file, $style = 'watermark')
    {
        $url = $this->getUrl($file, $style);

        return $url;
    }

    /**
     * 获取图片地址
     * @param string $file
     * @param string $style
     * @return mixed
     */
    public function getImageUrl($file, $style = 'watermark')
    {
        $config = $this->config;
        $url    = $this->storageRoot . $file;

       /* if (!empty($style)) {
            $url = $url . $config['style_separator'] . $style;
        }*/

        return $url;
    }

    /**
     * 获取文件地址
     * @param string $file
     * @param string $style
     * @return mixed
     */
    public function getUrl($file, $style = '')
    {
        $config = $this->config;
        $url    = $this->storageRoot . $file;

        /*if (!empty($style)) {
            $url = $url . $config['style_separator'] . $style;
        }*/

        return $url;
    }

     //转码
    public function zhuanma($path,$name){
        $command = "/ffmpeg-3.3.3/ffmpeg -i $path -f wav -ar 16000 -ac 1 $name 2>&1";  
        exec($command, $retval,$status);
        return $status;
    }

}
